package com.lumlord.common.base;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.lumlord.common.domain.Result;
import com.lumlord.common.domain.ServerInfo;
import com.lumlord.common.exception.BusinessException;
import com.lumlord.util.JdbcTemplateUtils;
import com.lumlord.util.RestTemplateUtil;
import com.lumlord.util.StringUtils;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Component;

/**
 * 服务调用
 * 
 * @author win 10
 *
 */
@Component
public class ServerRibbon  {

	public Result callPost(SERVER server, String action, Map<String,Object> parameter) throws BusinessException{
		return resultFilter(restTemplateUtil.post(getUrl(server, action), parameter));
	}

	public Result callGet(SERVER server, String action) throws BusinessException {
		return resultFilter(restTemplateUtil.get(getUrl(server, action)));
	}

	public Result callDelete(SERVER server, String action) throws BusinessException{
		return resultFilter(restTemplateUtil.delete(getUrl(server, action)));
	}
	
	private Result resultFilter(Result result) throws BusinessException{
		return result;
	}
	
 
	
	private String getUrl(SERVER server, String action) {
		String serverName = StringUtils. toUnderScoreCase(server.name());
		ServiceInstance serviceInstance = loadBalancerClient.choose(serverName.replaceAll("_", "-").toUpperCase());
		/*if(null!=serviceInstance) {
			String url = String.format("http://%s:%s/%s/"+action, serviceInstance.getHost(), serviceInstance.getPort(),serviceInstance.getServiceId().toLowerCase());
			System.out.println("url = "+url);
			
		}
		if(true) {
			ServerInfo serverInfo = jdbcTemplateUtils.queryOne("SELECT * FROM  yw_security_server.t_server WHERE SERVER_NAME=?", ServerInfo.class, server.name());
			return "http://"+serverInfo.getServer()+"/"+jdbcTemplateUtils.getColumn(new StringBuffer(server.name())).replaceAll("_", "-")+"/"+action;
		}*/
		
		String url = String.format("http://%s:%s/%s/"+action, serviceInstance.getHost(), serviceInstance.getPort(),serviceInstance.getServiceId().toLowerCase());
		return url;
	}
	
	public void setTooken(String tooken) {
		restTemplateUtil.setTooken(tooken);
	}
	
	@Autowired
	private JdbcTemplateUtils jdbcTemplateUtils; 
	@Autowired
 	private LoadBalancerClient loadBalancerClient;
	
	@Autowired
	private RestTemplateUtil restTemplateUtil;
	@Value("${lumlord.registryCenter}")
	private String registryCenter;

}
